package com.example.springboot.controller;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.py.mymodule.submodule.common.Result;
import org.py.mymodule.submodule.entity.Manager;
import org.py.mymodule.submodule.entity.Managerform;
import org.py.mymodule.submodule.mapper.ManagerMapper;
import org.py.mymodule.submodule.service.IManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-08-13
 */
@RestController
@RequestMapping("/manager")
public class ManagerController {
       @Autowired
       private ManagerMapper managerMapper;
    private  final String product = "Dysmsapi";
    // 产品域名,开发者无需替换
    private final String domain = "dysmsapi.aliyuncs.com";
    //rivate O 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    private final String accessKeyId = "LTAI5tK6hxHdtp95c9uYKxCA";
    private final String accessKeySecret = "zOTUIYKJXn4eWkKKLIUxZoi1REGWRM";
    private static final String AES = "AES";
    private static final String KEY = "1234567891234567"; // 16, 24, or 32 bytes key
    private static final Logger LOGGER = Logger.getLogger(ManagerController.class.getName());
    private String newcode;
    private List<String> codeList = new ArrayList<>();
    public SendSmsResponse sendSms(String telephone,String code) throws com.aliyuncs.exceptions.ClientException {

        // 可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        // 初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",accessKeyId ,accessKeySecret );
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        // 组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        // 必填:待发送手机号
        request.setPhoneNumbers(telephone);
        // 必填:短信签名-可在短信控制台中找到
        request.setSignName("行远");
        // 必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_471955203");
        // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + code + "\"}");

        // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");

        // hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){
            System.out.println("短信发送成功！");
        }else {
            System.out.println("短信发送失败！");
        }
        return sendSmsResponse;
    }

    //随机生成验证码
    public String getNewcode() {
        return newcode;
    }
    public void setNewcode(){
        Random random = new Random();
        newcode = String.valueOf((int)(1000+random.nextInt(9000)));  //每次调用生成一次四位数的随机数
    }
    //发送验证码
    @PostMapping("/sendCode")
    public Result  sample(@RequestParam String phone) throws Exception {
        setNewcode();
        newcode = String.valueOf(getNewcode());
        codeList.add(newcode);
        SendSmsResponse sendSms =sendSms(phone,newcode);//填写你需要测试的手机号码
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + sendSms.getCode());
        System.out.println("Message=" + sendSms.getMessage());
        System.out.println("RequestId=" + sendSms.getRequestId());
        System.out.println("BizId=" + sendSms.getBizId());
        if("OK".equals(sendSms.getCode())){
            return Result.success("发送成功",newcode);
        }else {
            return Result.error("发送失败");
        }

    }
    //验证码验证
    @PostMapping("/verifyCode")
    public Result verifyCode(@RequestParam String code) throws Exception {
        int rows = 0;
        for(String newcode:codeList) {
            if (code.equals(newcode)) {
                codeList.remove(newcode);
                return Result.success("验证成功");
            }
        }
        return Result.error("验证失败");
}
    //修改密码
    @PutMapping("/changePassword")
    public Result changePassword(@RequestParam String phone,@RequestParam String code,@RequestParam String password,@RequestParam String password1) throws Exception {
        int rows = 0;
        for (String newcode : codeList) {
            if (code.equals(newcode)) {
                codeList.remove(newcode);
                rows = 1;
                break;
            }
        }
        if (rows==0) {
            return Result.error("验证码错误");
        }

        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Manager manager = managerMapper.selectOne(queryWrapper);
        if(manager != null && password1.equals(password)){
            String newpassword = Encryption(password);
            manager.setPassword(newpassword);
            managerMapper.updateById(manager);
            manager.setPassword(password);
            return Result.success("success",manager);
        }else {
            return Result.error("两次密码不同或电话号码错误");
        }
    }
       //用户的登陆,通过账号密码
       @PostMapping("/login")
       public Map<String, Object> login(@RequestParam String account, @RequestParam String password) throws Exception {
           Map<String, Object> result = new HashMap<>();
           QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq("account",account);
           Manager manager = managerMapper.selectOne(queryWrapper);

           if (manager != null && manager.getPassword().equals(Encryption(password))) {
               manager.setPassword(password);
               result.put("status", "success");
               result.put("message", "登录成功");
               result.put("data", manager);
           } else {
               result.put("status", "error");
               result.put("message", "用户名或密码错误");
           }

           return result;
       }
    // 用户登录，通过电话
    @PostMapping("/loginByphone")
    public Map<String, Object> loginByUsername(@RequestParam String phone, @RequestParam String password) throws Exception {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        Manager manager = managerMapper.selectOne(queryWrapper);

        if (manager != null && manager.getPassword().equals(Encryption(password))) {
            manager.setPassword(password);
            result.put("status", "success");
            result.put("message", "登录成功");
            result.put("data", manager);
        } else {
            result.put("status", "error");
            result.put("message", "用户名或密码错误");
        }

        return result;
    }
    //ase解密
    public String decrypt(String encryptedPassword) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(KEY.getBytes(), AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword));
            return new String(original);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "解密失败", e);
            throw new RuntimeException("解密失败", e);
        }
    }
    //ase加密
    public String Encryption(String password) throws Exception{
        SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encryptedPassword = cipher.doFinal(password.getBytes(StandardCharsets.UTF_8));
        String encryptedPasswordBase64 = Base64.getEncoder().encodeToString(encryptedPassword);
        return encryptedPasswordBase64;
    }

    //员工的注册
    @PostMapping("/register")
    public Map<String, Object> register(@RequestParam String name, @RequestParam String phone, @RequestParam String password,@RequestParam String password1) {
        if (phone == null || phone.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("status", "error");
            result.put("message", "手机号不能为空");
            return result;
        }
        QueryWrapper<Manager> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("phone", phone);
        Manager Manager = managerMapper.selectOne(queryWrapper1);
        if(Manager!=null){
            Map<String, Object> result = new HashMap<>();
            result.put("status", "error");
            result.put("message", "该手机号已被注册");
            return result;
        }
        Map<String, Object> result = new HashMap<>();
        String account = new String();
        StringBuilder sb;
        Random random = new Random();
        Manager existingManager;
        // 检查两次输入的密码是否一致
        if (!password.equals(password1)) {
            result.put("status", "error");
            result.put("message", "两次密码不一致");
            return result;
        }

        do {
            int length = 6 + random.nextInt(10);
            sb = new StringBuilder(length);
            for (int i = 0; i < length; i++) {
                sb.append(random.nextInt(10)); // 生成0到9之间的随机数字
            }
            account = sb.toString();
            QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account", account);
            existingManager = managerMapper.selectOne(queryWrapper);
        } while (existingManager != null); // 如果账号已经存在，则重新生成


            try {
                String encryptedPasswordBase64 = Encryption(password);
                Manager newManager = new Manager();
                newManager.setAccount(account);
                newManager.setPhone(phone);
                newManager.setPassword(encryptedPasswordBase64); // 使用AES加密后的密码
                newManager.setName(name);
                int rows = managerMapper.insert(newManager);
                newManager.setPassword(password);
                if (rows > 0) {
                    result.put("status", "success");
                    result.put("message", "注册成功");
                    result.put("data", newManager);
                } else {
                    result.put("status", "error");
                    result.put("message", "注册失败");
                }
            } catch (Exception e) {
                result.put("status", "error");
                result.put("message", "加密过程中出现错误");
            }


        return result;
    }

    //账号的删除
    @DeleteMapping("/delete")
    public Map<String, Object> delete(@RequestParam String account,@RequestParam String password) {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        Manager manager = managerMapper.selectOne(queryWrapper);

        if (manager != null) {

            try {
                if(password.equals(Encryption(manager.getPassword()))){
                    int rows = managerMapper.deleteById(manager.getJobNumber());
                    if (rows > 0) {
                        result.put("status", "success");
                        result.put("message", "删除成功");
                    } else {
                        result.put("status", "error");
                        result.put("message", "删除失败");
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            result.put("status", "error");
            result.put("message", "该账号不存在");
        }

        return result;
    }
    //账号密码的修改
    @PutMapping("/updatepassword")
    public Map<String, Object> updatePassword(@RequestParam String account, @RequestParam String oldPassword,@RequestParam String newPassword) {
        Map<String, Object> result = new HashMap<>();
        QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        Manager manager = managerMapper.selectOne(queryWrapper);

        if (manager != null) {

            if(oldPassword.equals(decrypt(manager.getPassword())))
            {
                try {
                    manager.setPassword(Encryption(newPassword));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                int rows = managerMapper.updateById(manager);

                  if (rows > 0) {
                      result.put("status", "success");
                      result.put("message", "密码修改成功");
                  } else {
                      result.put("status", "error");
                      result.put("message", "密码修改失败");
                  }
            }
            else{
                result.put("status", "error");
                result.put("message", "密码错误");
            }
        } else {
            result.put("status", "error");
            result.put("message", "该账号不存在");
        }

        return result;
    }
    //管理员的查询
    @GetMapping("/getall")
    public List<Manager> selectmanager() throws Exception {
           List<Manager> managerList = managerMapper.selectList(null);
           for(Manager manager : managerList)
           {
               manager.setPassword(decrypt(manager.getPassword()));
           }
               return managerList;

    }
    //管理员的查询
    @GetMapping("/get/{id}")
    public List<Manager> selectidmanager(@PathVariable("id") Long id) throws Exception{
           QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq("job_number",id);
           List<Manager> manager = managerMapper.selectList(queryWrapper);
           if(manager==null){
               return null;
           }
           else{
               for(Manager manager1 : manager)
               {
                   manager1.setPassword(decrypt(manager1.getPassword()));
               }
               return manager;
           }
    }
    //管理员信息的修改
    @PutMapping("/update")
    public Result update(@RequestBody Managerform managerform) throws Exception{
           QueryWrapper<Manager> queryWrapper = new QueryWrapper<>();
           queryWrapper.eq("job_number", managerform.getJobNumber());
           Manager manager = managerMapper.selectOne(queryWrapper);
           if(manager!=null){
               manager.setAccount(managerform.getAccount());
               manager.setName(managerform.getName());

               int result = managerMapper.update(manager,queryWrapper);
               if(result>0){
                   return Result.success();
               }
               else {
                   return Result.error("修改失败");
               }
           }
           else {
               return Result.error("该账号不存在");
           }
    }





}
